package com.mayikt.exception;

import com.alibaba.fastjson.JSONObject;
import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import com.mayikt.base.enums.ApiBaseEnum;
import com.mayikt.base.enums.ApiResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends BaseApiService<JSONObject> {
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public BaseResponse<JSONObject> exceptionHandler(Exception e) {
        log.info("###全局捕获异常###,error:{}", e);
        return setResultError("系统错误!");
    }

    @ExceptionHandler({BizException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public BaseResponse<JSONObject> bizExceptionHandler(BizException bizException) {
        ApiBaseEnum apiBaseEnum = bizException.getApiEnum();
        String customMsg = bizException.getCustomMsg();
        log.error("intercept===BusinessException===info=={}", bizException.getMessage());
        if (apiBaseEnum != null && customMsg != null) {
            return setResultError(apiBaseEnum.getCode(),customMsg);
        }
        if (customMsg != null) {
            return setResultError(customMsg);
        }
        if (apiBaseEnum != null) {
            return setResultError(apiBaseEnum.getCode(),apiBaseEnum.getMsg());
        }
        return setResultError(ApiResponseEnum.INTERNAL_ERROR.getCode(),ApiResponseEnum.INTERNAL_ERROR.getMsg());
    }
}